package com.xhp.xtool.util.ftp;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.IOException;

public class FtpClientFactory implements PooledObjectFactory<FTPClient> {

	private FtpConfig ftpConfig;

	FtpClientFactory(FtpConfig ftpConfig) {
		this.ftpConfig = ftpConfig;
	}

	public FtpConfig getFtpConfig() {
		return ftpConfig;
	}

	@Override
	public PooledObject<FTPClient> makeObject() {
		FTPClient ftpClient = new FTPClient();
		return new DefaultPooledObject<>(ftpClient);
	}

	@Override
	public void destroyObject(PooledObject<FTPClient> pooledObject) {
		FTPClient ftpClient = pooledObject.getObject();
		try {
			ftpClient.logout();
			if (ftpClient.isConnected()) {
				ftpClient.disconnect();
			}
		} catch (IOException e) {
			throw new RuntimeException("断开连接失败！", e);
		}
	}

	@Override
	public boolean validateObject(PooledObject<FTPClient> pooledObject) {
		FTPClient ftpClient = pooledObject.getObject();
		try {
			return ftpClient.sendNoOp();
		} catch (IOException e) {
			throw new RuntimeException(e);
//			return false;
		}
	}

	@Override
	public void activateObject(PooledObject<FTPClient> pooledObject) throws Exception {
		FTPClient ftpClient = pooledObject.getObject();
		ftpClient.connect(ftpConfig.getHost(), ftpConfig.getPort());
		ftpClient.login(ftpConfig.getUserName(), ftpConfig.getPassWord());
		ftpClient.setControlEncoding(ftpConfig.getEncoding());
		ftpClient.changeWorkingDirectory(ftpConfig.getWorkDirectory());
		// 设置上传文件类型为二进制，否则将无法打开文件
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
	}

	@Override
	public void passivateObject(PooledObject<FTPClient> pooledObject) {
		FTPClient ftpClient = pooledObject.getObject();
		try {
			ftpClient.changeWorkingDirectory(ftpConfig.getRoot());
			ftpClient.logout();
			if (ftpClient.isConnected()) {
				ftpClient.disconnect();
			}
		} catch (IOException e) {
			throw new RuntimeException("关闭连接失败!" + e.getMessage());
		}
	}

}
